// https://vuex.vuejs.org/zh-cn/intro.html
// make sure to call Vue.use(Vuex) if using a module system
import Vue from 'vue'
import Vuex from 'vuex'
import { asyncWrap } from '../utils'
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        globalData: {
            userInfo: null, // userInfo:{avatarUrl:'',city:'',country:'',
            //   gender:'',language:'',nickName:'',province:'',},
            base: 'https://www.kaixin18.club',
            hua_base: 'https://aiba.kaixin18.club/',
            wx_config: {
                secret: '',
                appid: 'wx54510ab8ae4abd58'
            },
            WS: {
                socketMsgQueue: [], // ws断掉后积累的未发出消息
                ws_url: 'wss://aiba.kaixin18.club:3033',
                socketOpen: false
            },
            openid: ''
        },
        count: 0
    },
    mutations: {
        set_openid: (state, openid) => {
            const obj = state
            obj.globalData.openid = openid
        },
        set_userInfo: (state, userInfo) => {
            const obj = state
            obj.globalData.userInfo = userInfo
        },
        set_secret: (state, secret) => {
            const obj = state
            obj.globalData.wx_config.secret = secret
        },
        set_socketOpen: (state, is) => {
            const obj = state
            obj.globalData.WS.socketOpen = is
        },
        set_socketMsgQueue: (state, data) => {
            const obj = state
            obj.globalData.WS.socketMsgQueue = data
        },
        increment: (state) => {
            const obj = state
            obj.count += 1
        },
        decrement: (state) => {
            const obj = state
            obj.count += 1
        }
    },
    actions: {
        sendSocketMessage({ dispatch, state }, params) {
            if (state.globalData.WS.socketOpen) {
                wx.sendSocketMessage({ data: JSON.stringify(params) })
            } else {
                dispatch('connectWS')
                // this.connectWS()
                state.globalData.WS.socketMsgQueue.push(params)
            }
        },
        connectWS({ commit, state, dispatch }) {
            wx.connectSocket({
                url: state.globalData.WS.ws_url
            })
            wx.onSocketOpen(res => {
                console.log('WebSocket连接已打开store！')
                commit('set_socketOpen', true)
                // this.globalData.WS.socketOpen = true;

                for (var i = 0; i < state.globalData.WS.socketMsgQueue.length; i++) {
                    dispatch('sendSocketMessage', state.globalData.WS.socketMsgQueue[i])
                    // this.sendSocketMessage(this.globalData.WS.socketMsgQueue[i])
                }
                commit('set_socketMsgQueue', [])
                // this.globalData.WS.socketMsgQueue = []
                wx.onSocketClose(res => {
                    commit('set_socketOpen', false)
                    // this.globalData.WS.socketOpen = false;
                    console.log('WebSocket 已关闭！')
                })
            })
            wx.onSocketMessage(res => {
                console.log('收到服务器内容storejs：' + res.data)
            })
        },
        // 获取签名和appid，并且初始化函数
        initSetData({ commit, state }) {
            return new Promise(resolve => {
                if (!state.globalData.wx_config.secret) {
                    wx.request({
                        url: `${state.globalData.hua_base}get_appid_secret?appid=${
                            state.globalData.wx_config.appid}`,
                        method: 'GET',
                        success: res => {
                            const data = res.data
                            if (data.state === 401) {
                                commit('set_secret', data.data.secret)
                                // this.globalData.wx_config.secret = data.data.secret;
                                if (!wx.loginAsync) {
                                    wx.loginAsync = asyncWrap('login')
                                }
                                if (!wx.getUserInfoAsync) {
                                    wx.getUserInfoAsync = asyncWrap('getUserInfo')
                                }
                                if (!wx.reqAsync) {
                                    wx.reqAsync = asyncWrap('request')
                                }
                                resolve()
                            } else {
                                wx.showToast({
                                    title: '获取签名失败',
                                    icon: 'error',
                                    duration: 2000 // 持续的时间
                                })
                                resolve()
                            }
                        }
                    })
                }
            })
        },
        get_info({ commit, state, dispatch }) {
            return new Promise(async(resolve, reject) => {
                // 一定要先调用登录接口
                if (!state.globalData.wx_config.secret) {
                    await dispatch('initSetData')
                }
                const { code } = await wx.loginAsync()
                if (!code) {
                    wx.showToast({
                        title: '登录失败',
                        icon: 'error',
                        duration: 2000 // 持续的时间
                    })
                    return
                }
                await wx
                    .getUserInfoAsync()
                    .then(res => {
                        commit('set_userInfo', res.userInfo)
                    })
                    .catch(res => {
                        commit('set_userInfo', null)
                        wx.showToast({
                            title: '获取用户信息失败',
                            icon: 'error',
                            duration: 2000 // 持续的时间
                        })
                    })
                await wx
                    .reqAsync({
                        url: `${state.globalData.hua_base}get_openid?js_code=${code}&grant_type=authorization_code`
                    })
                    .then(res => {
                        const ret = res.data
                        if (ret.state === 401) {
                            const data = JSON.parse(ret.data)
                            // 保存用户openid等信息
                            commit('set_openid', data.openid)
                            console.log('获取openid成功:' + data.openid)
                        } else {
                            wx.showToast({
                                title: '获取openid失败',
                                icon: 'error',
                                duration: 2000 // 持续的时间
                            })
                        }
                    })
                resolve()
                console.log('get_info执行完毕')
            })
        }
    }
})

export default store
